/*
 * 折线类
 * @Author: ljb
 * @Date: 2018-09-13 11:47:25
 * @Last Modified by:ljb
 * @Last Modified time: 2018-09-13 11:47:25
 */

const PRIMARY_COLOR = '#ffffff'; // 线条颜色
const OPACITY_PRIMARY_COLOR = 'rgba(176, 103, 252, .3)'; // 端点透明色
/**
 *  折线
 */
export default class Line {
	constructor(coordinates, is_visible = false, color, opacity_color) {
		if (coordinates.length < 2) {
			throw new Error('坐标数量不能小于两个');
		}
		this.coordinates = coordinates;
		this.color = color;
		this.opacity_color = opacity_color;
		this.is_visible = is_visible;
	}

	/**
	 *  是否显示
	 */
	setVisible(is_visible) {
		this.is_visible = is_visible;
	}

	/**
	 *  划线
	 */
	draw(context) {
		if (!this.is_visible) {
			return false;
		}
		context.save();
		context.strokeStyle = this.color || PRIMARY_COLOR;
		context.fillStyle = this.color || PRIMARY_COLOR;

		const first = this.coordinates[0];
		const last = this.coordinates[this.coordinates.length - 1];

		context.beginPath();
		context.fillStyle = this.opacity_color || OPACITY_PRIMARY_COLOR;
		context.arc(first.x, first.y, 4, 0, 2 * Math.PI);
		context.arc(last.x, last.y, 4, 0, 2 * Math.PI);
		context.fill();

		context.beginPath();
		context.fillStyle = this.color || PRIMARY_COLOR;
		context.arc(first.x, first.y, 2, 0, 2 * Math.PI);
		context.arc(last.x, last.y, 2, 0, 2 * Math.PI);
		context.fill();

		context.lineWidth = 1;
		context.lineJoin = 'round';
		context.beginPath();
		// 划线
		this.coordinates.forEach((coordinate, index) => {
			if (index === 0) {
				context.moveTo(coordinate.x, coordinate.y);
			}
			context.lineTo(coordinate.x, coordinate.y);
		});
		// 端点
		context.stroke();
		context.restore(); // 方法从栈中弹出存储的图形状态并恢复
	}
}
